package com.cans.core.config;

import com.cans.auth.service.impl.CustomUserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.header.writers.frameoptions.XFrameOptionsHeaderWriter;

/**
 * Auther: shencan
 * Date: 2017/10/3
 * Description: spring security 配置信息
 */
@Configuration
public class WebSecurity extends WebSecurityConfigurerAdapter {

    @Bean
    UserDetailsService customUserService() {
        return new CustomUserService();
    }

    /**
     * 登陆成功
     * @return
     */
    @Bean
    public SimpleUrlAuthenticationSuccessHandler authenticationSuccessHandler() {
        AuthenticationSuccessHandler authenticationSuccessHandler = new AuthenticationSuccessHandler();
        return authenticationSuccessHandler;
    }

    /**
     * 登陆失败
     * @return
     */
    @Bean
    public SimpleUrlAuthenticationFailureHandler authenticationFailure() {
        AuthenticationFailureHandler authenticationFailureHandler = new AuthenticationFailureHandler();
        return authenticationFailureHandler;
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customUserService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers()
                .addHeaderWriter(
                        new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))
                .and().csrf().disable().formLogin().successHandler(authenticationSuccessHandler()).failureHandler(authenticationFailure())
                .loginProcessingUrl("/login")
                .loginPage("/index.html").permitAll()
                .and().authorizeRequests().anyRequest().authenticated()
                .and().sessionManagement().invalidSessionUrl("/timeout").maximumSessions(1).maxSessionsPreventsLogin(false)
                .expiredUrl("/timeout");
    }

}
